package pojo

import (
	"errors"
	"fmt"
	"github.com/topfreegames/pitaya/logger"
	"strconv"
	"strings"
	"time"
)

type AccountData struct {
	BaseData        `xorm:"-"`
	AccountId       int64     `xorm:"'accountId' default('0') notnull"`
	ChannelId       string    `xorm:"pk 'channelId' default('') notnull"`
	Username        string    `xorm:"pk 'username' default('') notnull"`
	AppId           string    `xorm:"pk 'appId'"`
	Password        string    `xorm:"'password' default('') notnull"`
	Macid           string    `xorm:"'macid' default('') notnull"`
	AllPlayerGuids  string    `xorm:"'allPlayerGuids' default('') notnull"`
	CreateTime      time.Time `xorm:"'createtime' default('null')"`
	ForbidLoginTime int64     `xorm:"'forbidlogintime' default('0') notnull"`
	ActiveCode      string    `xorm:"'activecode' default('') notnull"`
	DeviceModel     string    `xorm:"'deviceModel' default('') notnull"`
	IngotplayerId   int64     `xorm:"'ingotplayerId' default('0') notnull"`
	WorldId int `xorm:"-"`
}

func (a *AccountData) TableName() string {
	return "accountdata"
}

func (a *AccountData) GetDataKey() string {
	if a.AccountId <= 0 {
		return ""
	}

	return fmt.Sprintf("%d",a.AccountId)
}

func (a *AccountData) GetGuid() int64 {
	return a.AccountId
}

/**
从allGuids里面去除某个guid 返回之前的allGuids里面是否存在这个guid
 */
func (a *AccountData) CutPlayerGuid(guid int64) bool {
	if guid == 0 {
		return false
	}

	if len(a.AllPlayerGuids) == 0 {
		return false
	}

	strs := strings.Split(a.AllPlayerGuids,",")
	guidStr := strconv.FormatInt(guid,10)
	r := false
	arr := make([]string,0)
	for _,value := range strs {
		if len(value) == 0 {
			continue
		}

		if value == guidStr {
			r = true
			continue
		}

		arr = append(arr,value)
	}

	a.AllPlayerGuids = strings.Join(arr,",")
	return r
}
func (p *AccountData) AddPlayerGuid(guid int64) error {
	var err error
	if guid <= 0 {
		err = errors.New("guid can not below 0")
		logger.Log.Errorf("AddPlayerGuid failed,error:%s",err.Error())
		return err
	}


	if len(p.AllPlayerGuids) == 0{
		p.AllPlayerGuids = strconv.FormatInt(guid,10)
		return nil
	}

	guids := strings.Split(p.AllPlayerGuids,",")
	str := strconv.FormatInt(guid,10)
	for _,v := range guids {
		if v == str {
			err = errors.New("guid has exist in account data allguids")
			return err
		}
	}

	guids = append(guids,str)
	p.AllPlayerGuids = strings.Join(guids,",")
	return nil
}